package com.wizinno.android.urineflow.util;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author LiuMei
 * @date 2020-11-17.
 */
public class CommonUtil {

    public static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            LogUtils.i(e.getMessage());
            e.printStackTrace();
        }
        return hostIp;
    }

    public static String getMacDefault() {
        Enumeration<NetworkInterface> interfaceEnumeration = null;
        try {
            interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (interfaceEnumeration.hasMoreElements()){
            NetworkInterface networkInterface = interfaceEnumeration.nextElement();
            byte[] addr = new byte[0];
            try {
                addr = networkInterface.getHardwareAddress();
            } catch (SocketException e) {
                e.printStackTrace();
            }
            if (addr==null || addr.length==0){
                continue;
            }
            StringBuilder buf = new StringBuilder();
            for (byte b: addr){
                buf.append(String.format("%02X:",b));

            }
            if (buf.length()>0){
                buf.deleteCharAt(buf.length()-1);

            }
            return buf.toString();
        }
        return "";
    }


    public static void main(String[] args) {
        System.out.println(getHostIP());
    }
}
